package com.yuexun.beilunpatient.ui.registration.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.family.ui.Act_Family_List;
import com.yuexun.beilunpatient.ui.registration.adapter.RegistrationListAdapter;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentHistoryBean;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentHistoryData;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentLoginBean;
import com.yuexun.beilunpatient.ui.registration.model.impl.RegistrationModel;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AlreadyAppointmentPresenter;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentLoginPresenter;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAlreadyAppointmentView;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentLoginView;
import com.yuexun.beilunpatient.utils.DateUtil;
import com.yuexun.beilunpatient.widget.EmptyLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/10/18.
 */
public class Act_My_Registration extends BaseKJActivity implements IAlreadyAppointmentView, IAppointmentLoginView {

    @Bind(R.id.content_list)
    PullToRefreshList contentList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.tv_name)
    TextView tvName;

    ListView listView;
    RegistrationListAdapter adapter;
    AlreadyAppointmentPresenter presenter;
    AppointmentLoginPresenter loginPresenter;
    private int nowpage = 1;
    private int pagesize = 100;
    List<AppointmentHistoryData> dataAll = new ArrayList<>();
    List<AppointmentHistoryData> dataShow = new ArrayList<>();

    String memberNum;

    //判断是否正在显示
    protected boolean isVisible;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 10000:
                tvName.setText(data.getExtras().getString("name"));
                memberNum = data.getExtras().getString("memberNum");
                PreferenceHelper.write(aty, AppConfig.USER_INFO, AppConfig.MEMBENUMPROXY, memberNum);
                dataShow.clear();
                for(AppointmentHistoryData historyData : dataAll){
                    if(historyData.getMember_num().equals(memberNum)){
                        dataShow.add(historyData);
                    }
                }
                adapter.refresh(dataShow);
//                ApiGetData();
                break;
            default:
                break;
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_my_registration);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        presenter = new AlreadyAppointmentPresenter(new RegistrationModel(), this);
        loginPresenter = new AppointmentLoginPresenter(new RegistrationModel(), this);
        tvName.setText(PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_NAME));

        initList();

        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        loginPresenter.appointmentLogin(params);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isVisible = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isVisible = false;
    }

    private void ApiGetData(){
        String start = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String end = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getDayAfter(new Date(), 15));
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", pagesize + "");
        params.put("pageIndex", nowpage + "");
        params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
        params.put("searchEnddate", end);
        params.put("searchBegdate", start);
        params.put("resType", "1");
        params.put("memberNum", memberNum);
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        presenter.getAlreadyAppointmentList(params);
    }

    /**
     * 初始化列表
     */
    private void initList() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage = 1;
                ApiGetData();
            }
        });

        listView = contentList.getRefreshView();
        listView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        contentList.setPullRefreshEnabled(true);
        contentList.setPullLoadEnabled(true);
        ((FooterLoadingLayout) contentList.getFooterLoadingLayout()).setNoMoreDataText("无更多数据");

        adapter = new RegistrationListAdapter(listView, dataShow, R.layout.item_registration);
        listView.setAdapter(adapter);

        contentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                nowpage = 1;
                ApiGetData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiGetData();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                AppointmentHistoryData item = (AppointmentHistoryData) adapterView.getItemAtPosition(i);
                Bundle bundle = new Bundle();
//                bundle.putSerializable("regDetail", item);
                bundle.putString("scheduleGhxh", item.getSchedule_ghxh());
                bundle.putString("scheduleDate", item.getSchedule_date());
                Intent intent = new Intent(aty, Act_Registration_Detail.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.title_back, R.id.ll_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ll_name:
                Bundle bundle = new Bundle();
                Intent intent = new Intent(this, Act_Family_List.class);
                bundle.putString("type", "2");
                intent.putExtras(bundle);
                aty.startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public void getAlreadyAppointmentList(BaseEntity<AppointmentHistoryBean> baseEntity) {
        if(isVisible){
            if (contentList.isPullRefreshEnabled()) {
                contentList.onPullDownRefreshComplete();
            }
            if (baseEntity.getStatus().equals("200")) {
                if (baseEntity.getDatas().get(0).getCurrent_count() < pagesize) {
                    contentList.setHasMoreData(false);
                }else{
                    if (contentList.isPullLoadEnabled()) {
                        contentList.onPullUpRefreshComplete();
                    }
                }

                if (nowpage == 1) {
                    dataAll.clear();
                    dataAll = baseEntity.getDatas().get(0).getList();
                } else {
                    dataAll.addAll(baseEntity.getDatas().get(0).getList());
                }
                dataShow.clear();
                for(AppointmentHistoryData data : dataAll){
                    if(data.getMember_num().equals(memberNum)){
                        dataShow.add(data);
                    }
                }
                adapter.refresh(dataShow);

            }else {
                ViewInject.toast(baseEntity.getMessage());
            }

            if (dataShow.size() == 0) {
                emptyLayout.setErrorType(EmptyLayout.NODATA);
            } else {
                emptyLayout.dismiss();
            }
        }
    }

    @Override
    public void appointmentLogin(BaseEntity<AppointmentLoginBean> baseEntity) {
        if(isVisible){
            if(baseEntity.getStatus().equals("200")){
                AppointmentLoginBean loginBean = baseEntity.getDatas().get(0);
                if(loginBean.getRegisterState() == 0){
                    String filename = AppConfig.USER_INFO;
                    PreferenceHelper.write(aty, filename, AppConfig.ACCESSTOKEN, loginBean.getAccessToken());
                    PreferenceHelper.write(aty, filename, AppConfig.MEMBENUM, loginBean.getMembeNum());
                    PreferenceHelper.write(aty, filename, AppConfig.MEMBENUMPROXY, loginBean.getMembeNum());
                    PreferenceHelper.write(aty, filename, AppConfig.ISREGISTRATIONLOGIN, true);
                    PreferenceHelper.write(aty, filename, AppConfig.PHONE, loginBean.getPhone());

                    nowpage = 1;
                    memberNum = loginBean.getMembeNum();
                    ApiGetData();
                } else if(loginBean.getRegisterState() == 1){
                    Intent intent = new Intent(aty, Act_Appointment_Register.class);
                    startActivity(intent);
                }
                else if(loginBean.getRegisterState() == 2){
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", loginBean.getPhone());
                    Intent intent = new Intent(aty, Act_Appointment_Auth.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        }
    }
}
